package solution21;

/**
 * 21. Merge Two Sorted Lists
 * 混合插入有序链表
 * Merge two sorted linked lists and return it as a new list.
 * The new list should be made by splicing together the nodes of the first two lists.
 */
public class Solution {

    //具体思想就是新建一个链表，然后比较两个链表中的元素值，把较小的那个链到新链表中，
    //由于两个输入链表的长度可能不同，
    // 所以最终会有一个链表先完成插入所有元素，则直接另一个未完成的链表直接链入新链表的末尾。
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode dummy = new ListNode(0);
        ListNode current = dummy;
        while (l1 != null && l2!=null) {
            if (l1.val <= l2.val) {
                current.next = new ListNode(l1.val);
                current = current.next;
                l1 = l1.next;
            } else {
                current.next = new ListNode(l2.val);
                current = current.next;
                l2 = l2.next;
            }
        }
//        if (l1 != null) current.next = l1;
//        if(l2 != null) current.next = l2;
        current.next = (l1 != null) ? l1 : l2;
        return dummy.next;
    }

    // 递归解法
    // 比较当前两个节点值大小，如果l1的小，
    // 那么对于l1的下一个节点和l2调用递归函数，将返回值赋值给l1.next，然后返回l1；
    // 否则就对于l2的下一个节点和l1调用递归函数，将返回值赋值给l2.next，然后返回l2，
    public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        if (l1.val <= l2.val) {
            l1.next = mergeTwoLists2(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists2(l2.next, l1);
            return l2;
        }
    }

    public ListNode mergeTwoLists3(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode head = (l1.val < l2.val) ? l1 : l2;
        ListNode nonhead = (l1.val < l2.val) ? l2 : l1;
        head.next = mergeTwoLists3(head.next, nonhead);
        return head;
    }

    public ListNode mergeTwoLists4(ListNode l1, ListNode l2) {
        if (l1 == null || (l2 != null && l1.val > l2.val)) {
            ListNode t = l1; l1 = l2; l2 = t;
        }
        if (l1 != null) l1.next = mergeTwoLists4(l1.next, l2);
        return l1;
    }
}
